<?php
/*
  $Id:$
 */
$title = "留言簿";
 
if (isset($_POST) && $_POST) {
  /*
    TODO email telephone 验证
    TODO ajax form
   */
  $errors = array();
  
  if (!$_POST['content']) {
    $errors['content'] = '内容不能为空';
  }
  if (!$_POST['email']) {
    $errors['email'] = '邮箱不能为空';
  } else if (!preg_match('/^.*@.*$/', $_POST['email'])) {
    $errors['email'] = '邮箱格式不正确';
  }
  if ($_POST['telephone'] && !preg_match('/^[0-9-+]{5,30}$/', $_POST['telephone'])) {
    $errors['telephone'] = '电话号码格式不正确';
  }
  
  if ($errors) {
    include get_template('index');
    exit;
  }
  db_insert('message', array(
    'content'    => htmlspecialchars($_POST['content']),
    'author'     => htmlspecialchars($_POST['author']),
    'email'      => htmlspecialchars($_POST['email']),
    'telephone'  => htmlspecialchars($_POST['telephone']),
    'status'     => 'unread',
    'created_at' => 'now()',
    'updated_at' => 'now()',
  ));
  mail(EMAIL, 
      "=?UTF-8?B?" . base64_encode("您的网站[" . SITE_NAME . "]有一条新的留言") . "?=", 
      htmlspecialchars($_POST['content']) . "\n\n"
    . "----------------------------------------------\n\n"
    . '称呼:' .     htmlspecialchars($_POST['author']) . "\n"
    . '电子邮箱:' . htmlspecialchars($_POST['email']) . "\n"
    . '电话号码:' . htmlspecialchars($_POST['telephone']) . "\n"
    . '留言时间:' . date('Y-m-d H:i:s'), 
      "From: " . htmlspecialchars($_POST['author']) . " <" . htmlspecialchars($_POST['email']) . ">\nContent-Type: text/plain; charset=UTF-8");
  redirect('?module=message&action=success');
}

include get_template('index');